<template>
  <Drawer>
    <!-- 表单 -->
    <FosoForm
      ref="menuFormRef"
      :form-columns="formColumns"
      :form-data="formData"
      label-position="top"
      label-width="100px"
    >
      <template #icon> <IconPicker v-model="formData.icon" /> </template>
    </FosoForm>
  </Drawer>
</template>

<script lang="ts" setup>
import type { MenuInfoPlain } from '#/api/sys/model/menuModel';

import { IconPicker, useVbenDrawer, z } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { createMenu, getMenuById, updateMenu } from '#/api/sys/menu';
import { dictCache, refreshDictOptions } from '#/hooks/useDictCache';

import { MenuType } from '../type';
// 定义 emit 类型
interface Emit {
  (e: 'refresh', data?: any): void;
}
// 创建 emit 函数
const emit = defineEmits<Emit>();
// 表单实例
const menuFormRef = ref();

// 表单数据
const formData = ref<MenuInfoPlain>({
  menuType: 1, // 1-菜单 2-外链 3-按钮
  // trans: 'sys.menu.dashboard', // 国际化key
  // parentId: 1_000_000, // 0表示一级菜单
  // path: '/dashboard', // 路由路径
  // name: 'Dashboard', // 路由name
  // redirect: '/dashboard/workbench', // 重定向路径
  // component: '@/views/dashboard/index.vue', // 组件路径
  // sort: 10, // 排序值
  // disabled: false, // 是否禁用
  // title: '控制台', // 直接显示的标题
  status: 1, // 1启用 0禁用
  // icon: '', // 图标
  hideMenu: false, // 是否隐藏菜单
  hideBreadcrumb: false, // 是否隐藏面包屑
  KeepAlive: false, // 是否忽略缓存
  hideTab: false, // 是否隐藏标签页
  // frameSrc: '', // iframe地址（外链类型使用）
  carryParam: false, // 是否携带参数
  hideChildrenInMenu: false, // 是否隐藏子菜单
  affix: false, // 是否固定标签页
  // dynamicLevel: 1, // 动态路由层级
  // realPath: '/dashboard', // 真实路径
  // serviceName: 'DashboardService', // 微服务名称
  // permission: 'dashboard:view', // 权限标识
});

// 弹窗连接
const [Drawer, drawerApi] = useVbenDrawer({
  onConfirm: async () => {
    const { type, id } = drawerApi.getData<Record<string, any>>();
    await menuFormRef.value?.formRef?.validate(); // 验证表单
    if (type === 'addData') {
      addOrEditDictionaryHandle(formData.value);
    }
    if (type === 'editData') {
      addOrEditDictionaryHandle(formData.value, id);
    }
  },

  // 弹窗打开时触发
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      refreshDictOptions('menu'); // 获取菜单下拉数据
      // 设置默认值
      const { type, id } = drawerApi.getData<Record<string, any>>();
      // 新增
      if (type === 'addData') {
        await nextTick();
        menuFormRef.value?.formRef?.resetFields();
        // 确保表单已经挂载;
      }
      // 编辑打开弹窗时回显数据
      if (type === 'editData') {
        getMenuDetailInfo(id);
      }
    } else {
      // 关闭弹窗时重置表单
      menuFormRef.value.formRef.resetFields();
    }
  },
});

const menuHidden = ref(true); // 控制菜单项的显示和隐藏
const PageEleHidden = ref(false); // 控制页面元素项的显示和隐藏

// 表单配置项
const formColumns: any = computed(() => [
  {
    label: $t('sys.menu.type'),
    prop: 'menuType',
    xType: 'RadioGroup',
    span: 24,
    componentProps: {
      onChange: (val: number) => {
        menuHidden.value = false;
        if (val === MenuType.DIR) {
          PageEleHidden.value = false;
          menuHidden.value = true;
        }
        if (val === MenuType.PAGEDOM) {
          PageEleHidden.value = true;
          menuHidden.value = true;
        }
      },
      options: [
        { label: $t('sys.menu.directory'), value: MenuType.DIR },
        { label: $t('sys.menu.menu'), value: MenuType.MENU },
        { label: $t('sys.menu.pageDom'), value: MenuType.PAGEDOM },
      ],
    },
  },
  {
    label: $t('sys.menu.menuName'),
    prop: 'name',
    xType: 'Input',
    hidden: false,
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
    },
  },
  {
    label: $t('sys.menu.menuTitle'),
    prop: 'title',
    xType: 'Input',
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
    },
  },
  {
    label: $t('sys.menu.menuParent'),
    prop: 'parentId', // 绑定到 formData.gender
    xType: 'TreeSelect',
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),
      checkStrictly: true, // 严格检查
      clearable: true, // el-select 的属性
      data: [{ label: '根菜单', value: 0 }, ...(dictCache.get('menu') || [])],
    },
  },
  {
    label: $t('sys.menu.icon'),
    prop: 'icon',
    xType: 'Select',
  },
  {
    tip: $t('sys.apis.serviceNameHelpMessage'),
    label: $t('sys.menu.serviceName'),
    prop: 'serviceName',
    xType: 'Input',
    span: 24, // 自行配置行宽
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
    },
  },
  {
    tip: $t('sys.menu.pathHelp'),
    label: $t('sys.menu.routePath'),
    prop: 'path',
    xType: 'Input',
    hidden: PageEleHidden.value,
    span: 24, // 自行配置行宽
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
    },
  },
  {
    tip: $t('sys.menu.componentHelp'),
    label: $t('sys.menu.componentPath'),
    prop: 'component',
    xType: 'Input',
    hidden: menuHidden.value,
    rules: z
      .string()
      .regex(/^(\/[\w-]+)*(LAYOUT|IFrame)?$/gm, $t('common.wrongFormat')),
    span: 24, // 自行配置行宽
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
    },
  },
  {
    label: $t('sys.menu.redirectPath'),
    prop: 'redirect',
    xType: 'Input',
    hidden: menuHidden.value,
    span: 24, // 自行配置行宽
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
    },
  },
  {
    label: $t('sys.menu.frameSrc'),
    prop: 'frameSrc',
    xType: 'Input',
    hidden: menuHidden.value,
    span: 24, // 自行配置行宽
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
    },
  },
  {
    label: $t('sys.menu.realPath'),
    prop: 'realPath',
    xType: 'Input',
    span: 24, // 自行配置行宽
    hidden: menuHidden.value,
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
    },
  },
  {
    label: $t('sys.role.sort'),
    prop: 'sort',
    xType: 'Input',
    span: 12, // 自行配置行宽
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
    },
  },
  {
    label: $t('sys.menu.permission'),
    prop: 'permission',
    xType: 'Input',
    span: 12, // 自行配置行宽
    hidden: !PageEleHidden.value,
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
    },
  },
  {
    label: $t('sys.menu.dynamicLevel'),
    prop: 'dynamicLevel',
    xType: 'Input',
    hidden: PageEleHidden.value,
    span: 12, // 自行配置行宽
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
    },
  },
  {
    label: $t('sys.role.status'),
    prop: 'status',
    xType: 'RadioGroup',
    componentProps: {
      options: [
        { label: $t('common.form.start'), value: 1 },
        { label: $t('common.form.stop'), value: 0 },
      ],
    },
  },
  {
    label: $t('sys.menu.isKeepAlive'),
    prop: 'keepAlive',
    xType: 'RadioGroup',
    hidden: menuHidden.value,
    componentProps: {
      options: [
        { label: $t('common.form.yes'), value: true },
        { label: $t('common.form.no'), value: false },
      ],
    },
  },
  {
    label: $t('sys.menu.isHidden'),
    prop: 'hideMenu',
    xType: 'RadioGroup',
    hidden: PageEleHidden.value && menuHidden.value,
    componentProps: {
      options: [
        { label: $t('common.form.yes'), value: true },
        { label: $t('common.form.no'), value: false },
      ],
    },
  },
  {
    label: $t('sys.menu.isBreadcrumbShown'),
    prop: 'hideBreadcrumb',
    xType: 'RadioGroup',
    hidden: menuHidden.value,
    componentProps: {
      options: [
        { label: $t('common.form.yes'), value: true },
        { label: $t('common.form.no'), value: false },
      ],
    },
  },
  {
    label: $t('sys.menu.hideTab'),
    prop: 'hideTab',
    xType: 'RadioGroup',
    hidden: menuHidden.value,
    componentProps: {
      options: [
        { label: $t('common.form.yes'), value: true },
        { label: $t('common.form.no'), value: false },
      ],
    },
  },
  {
    label: $t('sys.menu.carryParam'),
    prop: 'carryParam',
    xType: 'RadioGroup',
    hidden: menuHidden.value,
    componentProps: {
      options: [
        { label: $t('common.form.yes'), value: true },
        { label: $t('common.form.no'), value: false },
      ],
    },
  },
  {
    label: $t('sys.menu.hideChildrenInMenu'),
    prop: 'hideChildrenInMenu',
    xType: 'RadioGroup',
    hidden: PageEleHidden.value && menuHidden.value,
    componentProps: {
      options: [
        { label: $t('common.form.yes'), value: true },
        { label: $t('common.form.no'), value: false },
      ],
    },
  },
  {
    label: $t('sys.menu.affix'),
    prop: 'affix',
    xType: 'RadioGroup',
    hidden: menuHidden.value,
    componentProps: {
      options: [
        { label: $t('common.form.yes'), value: true },
        { label: $t('common.form.no'), value: false },
      ],
    },
  },
]);

/**
 * @author Buke
 * @description 新增或者编辑
 * @param {Record<string, any>} formData - 表单数据对象。
 * @param {number} id - ID（可选）。
 * @returns {void}
 */
async function addOrEditDictionaryHandle(
  formData: Record<string, any>,
  id?: number,
): Promise<void> {
  const data = {
    ...formData,
    sort: Number(formData.sort),
    dynamicLevel: Number(formData.dynamicLevel),
    id,
  };
  id ? await updateMenu(data) : await createMenu(data);
  ElMessage.success($t('common.operateSuccess'));
  emit('refresh');
}

/**
 * @author Buke
 * @description 详情数据回显
 * @param {number} id - 要回显的职位ID。
 * @returns {void}
 */
async function getMenuDetailInfo(id: any): Promise<void> {
  drawerApi.setState({ loading: true });
  await getMenuById(id).then((res: MenuInfoPlain) => {
    formData.value = res;
    // 关闭加载中状态
    drawerApi.setState({ loading: false });
  });
}

// 监听菜单类型变化
watch(
  () => formData.value?.menuType,
  (val) => {
    menuHidden.value = false;
    if (val === MenuType.DIR) {
      PageEleHidden.value = false;
      menuHidden.value = true;
    }
    if (val === MenuType.PAGEDOM) {
      PageEleHidden.value = true;
      menuHidden.value = true;
    }
  },
);
</script>
